package com.ssy.lingxi.member.merchant.utils.baidu;

import com.alibaba.fastjson.JSONObject;

import java.io.IOException;
import java.net.URLEncoder;

/**
 * 百度智能云-身份证识别工具类
 * @author lqa
 * @version 2.0.0
 * @date 2022/1/11
 */
public class IdCardUtil {
    // 请求url
    static String url = "https://aip.baidubce.com/rest/2.0/ocr/v1/idcard";

    static byte[] originAesKey = null;

    public static String idCard(String filePath,String aesKey,String accessToken) throws Exception {
            // 文件路径
            byte[] imgData = FileUtil.readFile(filePath);
            String imgStr = encryptImg(aesKey, imgData);

            String imgParam = URLEncoder.encode(imgStr, "UTF-8");

            String param = "id_card_side=" + "front" +
                    "&image=" + imgParam +
                    "&AESEncry=" + true ;

            String encryptResult = HttpUtil.post(url, accessToken, param);

            return parseResult(encryptResult);
    }

    /**
     * 加密图片
     *
     * @param aesKey 百度智能云aesKey
     * @param imgData 图片数据
     * @return 操作结果
     * @throws Exception 异常
     */
    private static String encryptImg(String aesKey, byte[] imgData) throws Exception {
        originAesKey = AesKeyUtil.parseAesKey(aesKey);
        byte[] encImgBytes = AesUtil.encrypt(imgData, originAesKey);
        return Base64Util.encodeBase64(encImgBytes);
    }

    /**
     * 解密结果
     *
     * @param encryptResult 参数
     * @return 操作结果
     * @throws Exception 异常
     */
    private static String parseResult(String encryptResult) throws Exception {
        JSONObject obj = JSONObject.parseObject(encryptResult);
        String result = obj.getString("result");
        byte[] arr = Base64Util.decodeBase64(result);
        return new String(AesUtil.decrypt(arr, originAesKey));
    }
}
